<?php

namespace App\Http\Controllers\Api;

use App\Model\Position;
use App\Transformers\ProductTransformer;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\User;
use App\Service\UserService;
use App\Model\Product;
use Illuminate\Support\Facades\Redis;


class ShoppingCartController extends Controller
{
    /**
     * 添加购物车
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addShoppingCart(Request $request) {
        $return_data = UserService::getUser($request->header('AuthrizeOpenId'));
        if($return_data['errcode'] > 0) return $this->apiError($return_data['errmsg']);
        $user = $return_data['data'];
        $product_id = $request->input('product_id');
        $num = $request->input('num');
        $shopping_cart = User::getShoppingCart($user->id);
        $product = Product::findorfail($product_id);
        if($product->status == 'sale_out') return $this->apiError('此商品暂无');

        $list = $shopping_cart['list'];

        $whetherUpdateOrAdd = false;
        $updateKey = 0;
        $total_num = 0;//购物车商品总数量

        foreach ($list as $key => $value) {
            if($product_id == $value['product_id']) {
                $whetherUpdateOrAdd = true;
                $updateKey = $key;
            }
        }

        if($whetherUpdateOrAdd) {
            $total_num = $total_num + $num * 1 - $list[$updateKey]['num'] * 1;
            $list[$updateKey] = [
                'product_id' => $product_id,
                'num' => $num,
                'total_amount' => $product->discount * $num
            ];
        }else{
            $push_array = [
                'product_id' => $product_id,
                'num' => $num,
                'total_amount' => $product->discount * $num
            ];
            array_push($list, $push_array);
        }

        foreach ($list as $value2) {
            $total_num = $total_num * 1 + $value2['num'] * 1;
        }
        //list 有了
        $json_list = json_encode($list);
        User::updateShoppingCart($user->id, $json_list, $total_num);
        return $this->apiSuccess();
    }


    /**
     * 添加所有商品到购物车
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addShoppingCartOneTime(Request $request) {//随后修改
        $return_data = UserService::getUser($request->header('AuthrizeOpenId'));
        if($return_data['errcode'] > 0) return $this->apiError($return_data['errmsg']);
        $user = $return_data['data'];

        $addlist = $request->input('addlist');
        $shopping_cart = User::getShoppingCart($user->id);
        $list = $shopping_cart['list'];
        $total_num = 0;//购物车商品总数量

        foreach ($addlist as $al) {
            $product_id = $al['product_id'];
            $num = $al['num'];

            $product = Product::findorfail($product_id);
            if($product->status == 'sale_out') return $this->apiError('此商品暂无');

            $whetherUpdateOrAdd = false;
            $updateKey = 0;

            foreach ($list as $key => $value) {
                if($product_id == $value['product_id']) {
                    $whetherUpdateOrAdd = true;
                    $updateKey = $key;
                }
            }

            if($whetherUpdateOrAdd) {
                $total_num = $total_num + $num * 1 - $list[$updateKey]['num'] * 1;
                $list[$updateKey] = [
                    'product_id' => $product_id,
                    'num' => $num,
                    'total_amount' => $product->discount * $num
                ];
            }else{
                $push_array = [
                    'product_id' => $product_id,
                    'num' => $num,
                    'total_amount' => $product->discount * $num
                ];
                array_push($list, $push_array);
            }
        }

        foreach ($list as $value2) {
            $total_num = $total_num * 1 + $value2['num'] * 1;
        }


        //list 有了
        $json_list = json_encode($list);
        User::updateShoppingCart($user->id, $json_list, $total_num);
        return $this->apiSuccess();
    }


    /**
     * 分享出去
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sharePage(Request $request) {
        $return_data = UserService::getUser($request->header('AuthrizeOpenId'));
        if($return_data['errcode'] > 0) return $this->apiError($return_data['errmsg']);
        $user = $return_data['data'];
        $bistro_id = $request->input('bistro_id');
        $data['data'] = [
            'url_product_list' => env('APP_URL').'/api/getShoppingCartByOpenId?open_id='.$user->open_id.'&bistro_id='.$bistro_id
        ];
        return $this->apiSuccess($data);
    }

    /**
     * 没什么用
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getShoppingCartByOpenId(Request $request) {
        $bistro_id = $request->input('bistro_id');
        $products = Product::where('bistro_id', $bistro_id)->paginate(10);
        $data['data'] = [
            'products' => $this->factalPaginator($products, new ProductTransformer())
        ];
        return $this->apiSuccess($data);
    }

    /**
     * 创建请客
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function createDinner(Request $request) {//加™滴二维码
        $return_data = UserService::getUser($request->header('AuthrizeOpenId'));
        if($return_data['errcode'] > 0) return $this->apiError($return_data['errmsg']);
        $user = $return_data['data'];

        $qr_code = $request->input('qr_code');
        $password = $request->input('password');

        $position = Position::where('qr_code', $qr_code)->first();
        if(empty($position)) return $this->apiError('该位置不存在');

        $now_open_id_s_orignal = Redis::get('orderdinner:position_id||'.$position->id);
        $now_open_id_s = [];

        if(empty($now_open_id_s_orignal)) {
            $now_open_id_s = [];
        }else{
            $now_open_id_s = json_decode($now_open_id_s_orignal, true);
        }

        if(!empty($now_open_id_s) && in_array($request->header('AuthrizeOpenId'), $now_open_id_s)){
            return $this->apiError('已经创建过了，不需要重复创建', 40002);//4002是创建
        }

        if(empty($now_open_id_s)) {
            $now_open_id_s = [];
        }
        array_push($now_open_id_s, $request->header('AuthrizeOpenId'));
//        dd($now_open_id_s);
        Redis::setex('orderdinner:position_id||'.$position->id, 3600, json_encode($now_open_id_s));//记录哪个崽种请客
        Redis::setex('orderdinner:position_id||'.$position->id.'||openid||'.$request->header('AuthrizeOpenId').'password', 3600, $password);//记录哪个崽种请客

        return $this->apiSuccess();
    }

    /**
     * 添加商品到别人的购物车
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addShoppingCartByOpenid(Request $request) {
        $open_id = $request->input('open_id');
        $user = User::where('open_id', $open_id)->first();

        //座位的二维码 判断有没有请客 而且是不是这个人
        $qr_code = $request->input('qr_code');
        $position = Position::where('qr_code', $qr_code)->first();
        if(empty($position)) return $this->apiError('该位置不存在');
        $now_open_id_str = Redis::get('orderdinner:position_id||'.$position->id);
        if(empty($now_open_id_str)) {
            $now_open_id_s = [];
        }else{
            $now_open_id_s = json_decode($now_open_id_str, true);
        }

        if(empty($now_open_id_s) || !in_array($now_open_id_s, $open_id)) {
            return $this->apiError('这人根本就没请客，你个崽种');
        }

        $product_id = $request->input('product_id');
        $num = $request->input('num');
        $shopping_cart = User::getShoppingCart($user->id);
        $product = Product::findorfail($product_id);
        if($product->status == 'sale_out') return $this->apiError('此商品暂无');

        $list = $shopping_cart['list'];

        $whetherUpdateOrAdd = false;
        $updateKey = 0;
        $total_num = 0;//购物车商品总数量

        //改变购物车
        foreach ($list as $key => $value) {
            if($product_id == $value['product_id']) {
                $whetherUpdateOrAdd = true;
                $updateKey = $key;
            }
        }

        if($whetherUpdateOrAdd) {
            $total_num = $total_num + $num * 1 - $list[$updateKey]['num'] * 1;
            $list[$updateKey] = [
                'product_id' => $product_id,
                'num' => $num,
                'total_amount' => $product->discount * $num
            ];
        }else{
            $push_array = [
                'product_id' => $product_id,
                'num' => $num,
                'total_amount' => $product->discount * $num
            ];
            array_push($list, $push_array);
        }

        foreach ($list as $value2) {
            $total_num = $total_num * 1 + $value2['num'] * 1;
        }
        //list 有了
        $json_list = json_encode($list);
        User::updateShoppingCart($user->id, $json_list, $total_num);
        return $this->apiSuccess();
    }

    /**
     * 修改购物车
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateShoppingCart(Request $request) {
        $return_data = UserService::getUser($request->header('AuthrizeOpenId'));
        if($return_data['errcode'] > 0) return $this->apiError($return_data['errmsg']);
        $user = $return_data['data'];
        $product_id = $request->input('product_id');
        $num = $request->input('num');
        //查看购物车中有什么东西
        $shopping_cart = User::getShoppingCart($user->id);
//        dd($shopping_cart);
    }

    /**
     * 获取购物车
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getShoppingCart(Request $request) {
        $return_data = UserService::getUser($request->header('AuthrizeOpenId'));
        if($return_data['errcode'] > 0) return $this->apiError($return_data['errmsg']);
        $user = $return_data['data'];
        $shopping_cart = User::getShoppingCart($user->id);

        foreach ($shopping_cart['list'] as $key => $value) {
            $product = Product::find($value['product_id']);
            $shopping_cart['list'][$key]['product_information'] = $product;
        }
        $data['data'] = [
            'shopping_cart' => $shopping_cart
        ];
        return $this->apiSuccess($data);
    }

    /**
     * 删除购物车
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteShoppingCart(Request $request) {
        $return_data = UserService::getUser($request->header('AuthrizeOpenId'));
        if($return_data['errcode'] > 0) return $this->apiError($return_data['errmsg']);
        $user = $return_data['data'];
        $product_ids = $request->input('product_ids');
        $shopping_cart = User::getShoppingCart($user->id);
        $list = $shopping_cart['list'];
        foreach ($list as $key => $value) {
            foreach($product_ids as $value2) {
                if($value2 == $value['product_id']) {
                    unset($list[$key]);
                }
            }
        }

        $total_num = 0;
        $arr_new_list = [];

        foreach ($list as $value2) {
            $total_num = $total_num * 1 + $value2['num'] * 1;
            array_push($arr_new_list, $value2);
        }

        //list 有了
        $json_list = json_encode($arr_new_list);
        User::updateShoppingCart($user->id, $json_list, $total_num);
        return $this->apiSuccess();
    }
}
